package com.totobox.apps.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.totobox.apps.Const;
import com.totobox.apps.R;
import com.totobox.apps.common.ImageDownloader;
import com.totobox.apps.common.MoveActivity;
import com.totobox.apps.common.MovieCustomDialog;
import com.totobox.apps.common.TotoIFData;
import com.totobox.apps.common.Util;

public class MyTotoFolderActivity extends BasicActivity implements OnScrollListener{
	
	private ProgressDialog progressDialog;
	final public int PROGRESS_DIALOG = 0;
	final public int MOVIE_DIALOG = 1;	//동영상 알럿창
	
	public Thread dataThread = null;
	public Handler handler = new Handler();
	
	public List<Map<String,String>> folderList;
	public Map<String,String> folderData;
	
	public ListView folder;
	public FolderListAdapter listAdapter;
	
	//더 불러오기시 락 건다.
	private boolean mLockListView;
	
	//체크 박스 리스트
	public List<CheckBox> checkList = new ArrayList<CheckBox>();
	
	public List<ImageView> imageList = new ArrayList<ImageView>();
	
	public boolean onOff = false;
	public LinearLayout menu_footer;
	
	public ImageButton btn_all;
	public ImageButton btn_dn;
	public ImageButton btn_r_dn;
	public ImageButton btn_play;
	public ImageButton btn_stream;
	public ImageButton btn_cancel;
	
	public String iTotalCount = "0";
	public String iTotalPageCount = "0";
	
	//전체 선택 여부
	public boolean isAllCheck = true;
	
	public boolean isSearch = true;
	
	public ImageDownloader imageDownloader = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.my_folder_list);
        
        //초기화
        checkList.clear();
        
        folder = (ListView)findViewById(R.id.folder_list);
        folder.setOnItemClickListener(this);
        
        menu_footer = (LinearLayout)findViewById(R.id.menu_footer);
        
		//상단 타이틀 초기화
        super.initTitle();
        
        //해당 액티비티만 검색 가능
        btn_title_right.setClickable(true);
        
		//상단 메뉴
        super.showTopMenu(MyTotoFolderActivity.this);
        
        //하단 메뉴 세팅
        super.setFooterMenu(this);
        
        //하단 down 메뉴
        this.initFooterMenu();
        
        
		showDialog(PROGRESS_DIALOG);
		
		folderData = Const.mainFolder.get(Const.MENU);
		
		dataThread = new Thread(null, jsonList);
    	dataThread.start();
    }

	@Override
	public void onClick(View v) {
		
		if(v == btn_dn){
			this.setClickable(true);
			this.onDownButton();
		}
		else if(v == btn_play){
			this.setClickable(true);
			this.onPlayButton();
		}
		else if(v == btn_all){
			this.setAllChecked();
		}
		else if(v == btn_r_dn){

			int chkCnt = 0;
			if(checkList != null && !checkList.isEmpty()){
				int size = checkList.size();
				
				Const.dnQueue.clear();
				
				for(int i = 0 ; i < size ; i++){
					if(checkList.get(i).isChecked()){
						//체크된 다운 파일을 선별한다.
						Const.dnQueue.add(folderList.get(checkList.get(i).getId()));
						chkCnt++;
					}
				}
			}
			
			if(chkCnt == 0){
				super.showText(this, "선택된 파일이 없습니다. ");
			}
			else{
				if("VOD".equals(Const.MENU)){		//동영상 일경우 알럿을 띄운다
					showDialog(MOVIE_DIALOG);	
				}
				else { 
					MoveActivity go = new MoveActivity(MyTotoFolderActivity.this , TotoFileConfirmActivity.class);
					go.startActivity();		
				}
			}
		}
		else if(v == btn_title_left){
			finish();
		}
		else if(v == btn_title_right){
			
			if(!isSearch){
				if(searchMenu != null){
					searchMenu.removeAllViews();
				}
			}
			else{
				super.showSearchMenu();
			}
			isSearch =  !isSearch;
		}
		else if(btn_stream == v){
			
			int chkCnt = 0;
			if(checkList != null && !checkList.isEmpty()){
				int size = checkList.size();
				
				Const.dnQueue.clear();
				
				for(int i = 0 ; i < size ; i++){
					if(checkList.get(i).isChecked()){
						//체크된 다운 파일을 선별한다.
						int index = checkList.get(i).getId();
						Const.dnQueue.add(folderList.get(index));
						chkCnt++;
					}
				}
			}
			
			if(chkCnt == 0){
				super.showText(this, "선택된 파일이 없습니다. ");
			}
			else{
				if("VOD".equals(Const.MENU)){
					MoveActivity go = new MoveActivity(MyTotoFolderActivity.this , TotoVodPlayerActivity.class);
					go.startActivity();
				}
				else{
					MoveActivity go = new MoveActivity(MyTotoFolderActivity.this , TotoMusicPlayerActivity.class);
					go.startActivity();
				}
			}
		}
		else if(btn_cancel == v){
			this.setAllUnChecked();
			this.initFooterMenu();
		}
	}
    
	/**
	 * 다운로드 파일 리스트
	 */
	private Runnable jsonList = new Runnable() {
    	public void run() {
    		try {
    			
    			String biFolderSeq = folderData.get("biFolderSeq");
    			String iFolderDepth = folderData.get("iFolderDepth");
    			String vcFolderKey = folderData.get("vcFolderKey");
    			String iPage = "0";
    			String biCursorSeq = "0";
    			String iPageSize = "10";
    			String vcSearchText = "";
    			String vcAgent = "android";
    			
    			folderList = TotoIFData.FoldernFile(biFolderSeq , iFolderDepth , vcFolderKey , iPage , biCursorSeq , iPageSize , vcSearchText , vcAgent);
    			
		    	handler.post(dataResults);
		    	
    		} catch (Exception e) {
    			Log.d("partData : ", e.toString());
    		}
    	}
    };
    
    /**
     * json 데이터
     */
	private Runnable dataResults = new Runnable() {
    	public void run() {
    		try {
    			if (folderList != null) {
    				
    				listAdapter = new FolderListAdapter(MyTotoFolderActivity.this , R.layout.item_folder_list ,  folderList);
    				folder.setOnScrollListener(MyTotoFolderActivity.this);
    				folder.setAdapter(listAdapter);
    			}
    			else{
    				showNotFoundData();
    			}
    			
    	    	progressDialog.dismiss();
    	    	MyTotoFolderActivity.this.removeDialog(PROGRESS_DIALOG);
    	    	
    		} catch (Exception e) {
    			Log.e("xml-data", e.toString());
    		}

    	}
    };
    
    private void showNotFoundData() {
    	Toast toast = Toast.makeText(this, "다운로드 파일이 없습니다.", Toast.LENGTH_SHORT);
    	toast.show();
    }
    
    class FolderListAdapter extends ArrayAdapter {
    	
    	int courser = 0;
    	private int layout;
    	private Activity context;
    	List<Map<String,String>> list;
    	
    	
    	@SuppressWarnings("unchecked")
    	public FolderListAdapter(Activity context , int layout , List<Map<String,String>> list){
    		
    		super(context , layout , list);
    		
    		this.context = context;
    		this.list = list;
    		this.layout = layout;
    	}
    	
    	public View getView(int position , View convertView , ViewGroup parent){
    		
    		Map<String,String> map = list.get(position);

    		LayoutInflater inflater = context.getLayoutInflater();
    		View view = inflater.inflate(layout, null);
    		
    		RelativeLayout layout_item = (RelativeLayout)view.findViewById(R.id.layout_item);
    		
    		ImageView list_icon = (ImageView)view.findViewById(R.id.list_icon);
    		TextView txt_list_name = (TextView)view.findViewById(R.id.txt_list_name);
    		TextView txt_detail = (TextView)view.findViewById(R.id.txt_detail);
    		txt_list_name.setText(Util.getCutstring(map.get("vcName"),60,"..."));
    		
    		String cType = map.get("cType");
    		if("F".equals(cType)){	//folder
    			
    			if("IMG".equals(Const.MENU)) list_icon.setImageDrawable(getResources().getDrawable(R.drawable.default_photo));
    			else if("VOD".equals(Const.MENU)) list_icon.setImageDrawable(getResources().getDrawable(R.drawable.default_video));
    			else if("AUD".equals(Const.MENU)) list_icon.setImageDrawable(getResources().getDrawable(R.drawable.default_music));
    			else if("ETC".equals(Const.MENU)) list_icon.setImageDrawable(getResources().getDrawable(R.drawable.default_etc));
    			else  list_icon.setImageDrawable(getResources().getDrawable(R.drawable.default_folder));
    			
    			txt_detail.setText(map.get("cType") + " , " + map.get("biFileSizeByFolder"));
    		}
    		else{//file
    			
    			LinearLayout layout_chekbox = (LinearLayout)view.findViewById(R.id.layout_chekbox);
    			
    			//CheckBox file_check = new CheckBox(MyTotoFolderActivity.this);
    			CheckBox file_check = (CheckBox)view.findViewById(R.id.file_check);
        		file_check.setId(courser);
        		//file_check.setVisibility(View.INVISIBLE);
        		checkList.add(file_check);
        		//layout_chekbox.addView(file_check);
        		
    			layout_item.setBackgroundDrawable(getResources().getDrawable(R.drawable.folder_basic_02));
    			

    			int fileSize = Integer.parseInt(map.get("biFileSize"))/1024/1024;
    			int playTime = Integer.parseInt(map.get("vcFilePlayTime"));
    			
    			txt_detail.setText(map.get("dtRegDate").substring(0, 10) + "  " + fileSize + "MB " + playTime/60/60 + ":" + playTime/60%60 + ":" + playTime%60);
    			
				imageDownloader.download(map.get("vcThumbNailInfo"),list_icon);
    		}
    		courser++;
    		return  view;
    	}
    }
    
	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
		
		Map<String,String> map = folderList.get(position);
		
		if("IMG".equals(Const.MENU)){
			
			if("C".equals(Util.trim(map.get("cType")))){
				
				int j = 0;
				int size = folderList.size();
				Const.dnQueue.clear(); 
				int curPosition = 0;
				for(int i = 0 ; i < size ; i++){
					
					if("C".equals(folderList.get(i).get("cType"))){
						//체크된 다운 파일을 선별한다.
						Const.dnQueue.add(folderList.get(i));
						if(position == i) curPosition = j;
						
						j++;
					}
				}
				//서버데이터를 넘긴다.
				Const.isServer = true;
				
				MoveActivity go = new MoveActivity(MyTotoFolderActivity.this , TotoPhotoViewActivity.class);
				go.putExtra("curPosition", curPosition);
				//파일 상세 정보
				go.startActivity();
			}
		}
		else{
			if("F".equals(Util.trim(map.get("cType")))){
				
				showDialog(PROGRESS_DIALOG);
				
				folderData.putAll(map);
				dataThread = new Thread(null, jsonList);
		    	dataThread.start();
			}
			else{
				
				Const.dnQueue.clear();
				MoveActivity go = new MoveActivity(MyTotoFolderActivity.this , TotoFileDtailActivity.class);
				Const.dnQueue.add(map);
				go.startActivity();
			}
		}
	}
	
	
	/**
	 * 체크 박스 체크 가능 상태 변경
	 * @param isAble
	 */
	public void setClickable(boolean isAble){
		
		if(checkList != null && !checkList.isEmpty()){
			
			int size = checkList.size();
			
			for(int i = 0 ; i < size ; i++){
				checkList.get(i).setClickable(isAble);
				checkList.get(i).setVisibility(View.VISIBLE);
			}
		}
	}
	
	/**
	 * 전체 체크
	 * @param isAble
	 */
	public void setAllChecked(){
		
		if(checkList != null && !checkList.isEmpty()){
			
			int size = checkList.size();
			
			for(int i = 0 ; i < size ; i++){
				
				checkList.get(i).setChecked(isAllCheck);
			}
		}
		
		//현재의 반대를 넣는다.
		isAllCheck = !isAllCheck;
	}
	
	/**
	 * 전체 체크
	 * @param isAble
	 */
	public void setAllUnChecked(){
		
		if(checkList != null && !checkList.isEmpty()){
			
			int size = checkList.size();
			
			for(int i = 0 ; i < size ; i++){
				
				checkList.get(i).setChecked(false);
			}
		}
		
		//현재의 반대를 넣는다.
		isAllCheck = !isAllCheck;
	}
	
	/**
	 * 전체 체크
	 * @param isAble
	 */
	public void setCanceled(){
		
		if(checkList != null && !checkList.isEmpty()){
			
			int size = checkList.size();
			
			for(int i = 0 ; i < size ; i++){
				
				checkList.get(i).setChecked(false);
				checkList.get(i).setVisibility(View.INVISIBLE);
				
			}
		}
	}

	@Override
	protected Dialog onCreateDialog (int id) {
		switch (id) {
		case PROGRESS_DIALOG:
			
			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("목록 로딩중 입니다.");
			return progressDialog;
			
		case MOVIE_DIALOG:
			
			Dialog dialog = new MovieCustomDialog(this);
    		dialog.show();
			
			return null;
		default:
			
			return null;
		}
	}
	
	//------------------------------------- 하단 4개 메뉴 구성-------------------------------
	
	public void onPlayButton(){
		View v = null;
		
		//기존에 가지고 있던 뷰 제거
		if(menu_footer != null && menu_footer.getChildCount() >0) menu_footer.removeAllViews();
		
		//새로운 뷰를 추가 
		LayoutInflater inflater = this.getLayoutInflater();
				
		v = inflater.inflate(R.layout.folder_list_footer_vod_btn, null);
		
		btn_all = (ImageButton) v.findViewById(R.id.btn_all_check);
		btn_stream = (ImageButton) v.findViewById(R.id.btn_play);
		btn_cancel = (ImageButton) v.findViewById(R.id.btn_cancel);
		
		btn_all.setOnClickListener(this);
		btn_stream.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);
		
		menu_footer.addView(v);
		
	}
	
	public void onDownButton(){
		
		//기존에 가지고 있던 뷰 제거
		if(menu_footer != null && menu_footer.getChildCount() >0) menu_footer.removeAllViews();
				
		//새로운 뷰를 추가 
		LayoutInflater inflater = this.getLayoutInflater();
		
		View v = inflater.inflate(R.layout.folder_list_footer_btn, null);
		
		btn_all = (ImageButton) v.findViewById(R.id.btn_all_check);
		btn_r_dn = (ImageButton) v.findViewById(R.id.btn_real_down);
		
		btn_cancel = (ImageButton) v.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(this);
		
		btn_all.setOnClickListener(this);
		btn_r_dn.setOnClickListener(this);
		menu_footer.addView(v);
		
	}
	
	//초기 버튼
	public void initFooterMenu(){
		View v = null;
		
		//기존에 가지고 있던 뷰 제거
		if(menu_footer != null && menu_footer.getChildCount() >0) menu_footer.removeAllViews();
		
		//새로운 뷰를 추가 
		LayoutInflater inflater = this.getLayoutInflater();
			
		if("VOD".equals(Const.MENU) || "AUD".equals(Const.MENU)){
			btn_play = new ImageButton(this);
			btn_play.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_play));
			btn_play.setOnClickListener(this);
			menu_footer.addView(btn_play);
			
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(3, ViewGroup.LayoutParams.WRAP_CONTENT,0.0F);
			LinearLayout linear = new LinearLayout(this);
			linear.setLayoutParams(params);
			
			menu_footer.addView(linear);
		}
		
		btn_dn = new ImageButton(this);
		btn_dn.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_down));
		btn_dn.setOnClickListener(this);
		
		menu_footer.addView(btn_dn);
		
	}
	
	//-------------------------------------------------------------------------------------
	
	//---------------------------------- 리스트 페이징 소스다 -------------------------------- 
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount){
		
		// 현재 가장 처음에 보이는 셀번호와 보여지는 셀번호를 더한값이 전체의 숫자와 동일해지면 가장 아래로 스크롤 되었다고
		// 가정합니다.
		int count = totalItemCount - visibleItemCount;
		
		if(firstVisibleItem >= count && totalItemCount != 0 && mLockListView == false){
			
			//super.showText(this, "리스트 끝이다...");
			//addItems(50);
		}	
	}
	
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState){
		
	}
	
	/**
	 * 임의의 방법으로 더미 아이템을 추가합니다.
	 * 
	 * @param size
	 */
	private void addItems(final int size)
	{
		// 아이템을 추가하는 동안 중복 요청을 방지하기 위해 락을 걸어둡니다.
		mLockListView = true;
		
		Runnable run = new Runnable()
		{
			@Override
			public void run()
			{
				for(int i = 0 ; i < size ; i++)
				{
					//mRowList.add("Item " + i);
				}
				
				// 모든 데이터를 로드하여 적용하였다면 어댑터에 알리고 리스트뷰의 락을 해제합니다.
				listAdapter.notifyDataSetChanged();
				mLockListView = false;
			}
		};
		
		// 속도의 딜레이를 구현하기 위한 꼼수
		Handler handler = new Handler();
		handler.postDelayed(run, 5000);
	}
	//--------------------------------------- 페이징 ------------------------------------
	
	@Override
    protected void onDestroy() {
		
		if(imageList != null && !imageList.isEmpty()){
			int size = imageList.size();
			for(int i = 0 ; i < size ; i++)
				if(imageList.get(i) != null)
					this.recycleBitmap(imageList.get(i));
		}
		
        super.onDestroy();
        
    }
     
    @Override
	protected void onPause() {
    	if(imageList != null && !imageList.isEmpty()){
			int size = imageList.size();
			for(int i = 0 ; i < size ; i++)
				if(imageList.get(i) != null)
					this.recycleBitmap(imageList.get(i));
		}
    	super.onPause();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
    	
    	//리트스 데이터 초기화 
    	checkList.clear();
    	imageList.clear();
    	
    	imageDownloader = new ImageDownloader();
    	//--------------------- 
    	
		super.onStart();
	}

	@Override
	protected void onResume() {
		//리트스 데이터 초기화 
    	checkList.clear();
    	imageList.clear();
    	
    	imageDownloader = new ImageDownloader();
    	//--------------------- 
		super.onResume();
	}

	private void recycleBitmap(ImageView iv) {
    	
    	Drawable d = iv.getDrawable();
    	if (d instanceof BitmapDrawable) {
    		Bitmap b = ((BitmapDrawable)d).getBitmap();
    		b.recycle();
        }
    	// 현재로서는 BitmapDrawable 이외의 drawable 들에 대한 직접적인 메모리 해제는 불가능하다.
         
    	d.setCallback(null);
    }
	
}